import { NextResponse } from "next/server";

/**
 * Pre-flight readiness probe. The UI pings this before sending a prompt so
 * we refuse fast if the agent or a downstream dependency is unhealthy,
 * rather than burning an LLM turn on a request that would loop or 500.
 */
export const runtime = "nodejs";
export const dynamic = "force-dynamic";

export async function GET() {
  const agentApi =
    process.env.EUGENE_AGENT_API_URL ?? "http://eugene_agent_ws:8000/agent/api";
  try {
    const res = await fetch(`${agentApi}/health/ready`, {
      cache: "no-store",
      signal: AbortSignal.timeout(4000),
    });
    const body = await res.text();
    return new NextResponse(body, {
      status: res.status,
      headers: { "Content-Type": "application/json" },
    });
  } catch (e) {
    return NextResponse.json(
      { status: "DOWN", error: (e as Error).message },
      { status: 503 }
    );
  }
}
